import { defineStore } from 'pinia'

export const useUserAuthStore = defineStore('userAuth', {
  state: () => ({
    isLogin: false,
    token: '',
    userInfo: {
      id: null,
      username: '',
      email: '',
      phone: '',
      real_name: '', // 数据库字段名
      user_type: 'user', // 数据库字段名：user, lawyer, admin
      avatar: '',
      description: '',
      status: 1, // 用户状态：1-启用，0-禁用
      create_time: '', // 创建时间
      update_time: '', // 更新时间
      last_login_time: '', // 最后登录时间
      // 扩展字段
      role: '', // 兼容旧版本
      permissions: [], // 用户权限列表
      settings: {} // 用户设置
    }
  }),
  
  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo.id,
    
    // 获取用户名
    username: (state) => state.userInfo.username,
    
    // 获取用户类型
    userType: (state) => state.userInfo.user_type,
    
    // 获取真实姓名
    realName: (state) => state.userInfo.real_name,
    
    // 获取用户邮箱
    email: (state) => state.userInfo.email,
    
    // 获取用户手机
    phone: (state) => state.userInfo.phone,
    
    // 获取用户头像
    avatar: (state) => state.userInfo.avatar || '/default-avatar.png',
    
    // 判断是否为管理员
    isAdmin: (state) => state.userInfo.user_type === 'admin',
    
    // 判断是否为律师
    isLawyer: (state) => state.userInfo.user_type === 'lawyer',
    
    // 判断是否为普通用户
    isUser: (state) => state.userInfo.user_type === 'user',
    
    // 判断用户是否启用
    isActive: (state) => state.userInfo.status === 1,
    
    // 获取用户权限
    permissions: (state) => state.userInfo.permissions || [],
    
    // 检查是否有特定权限
    hasPermission: (state) => (permission) => {
      return state.userInfo.permissions?.includes(permission) || false
    }
  },
  
  actions: {
    // 用户登录
    login({ token, userInfo }) {
      this.isLogin = true
      this.token = token
      
      // 合并用户信息，保持向后兼容
      this.userInfo = {
        ...this.userInfo,
        ...userInfo,
        // 兼容旧版本的role字段
        role: userInfo.user_type || userInfo.role || 'user'
      }
      
      // 存储到本地存储
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      localStorage.setItem('isLogin', 'true')
    },
    
    // 用户登出
    logout() {
      this.isLogin = false
      this.token = ''
      this.userInfo = {
        id: null,
        username: '',
        email: '',
        phone: '',
        real_name: '',
        user_type: 'user',
        avatar: '',
        description: '',
        status: 1,
        create_time: '',
        update_time: '',
        last_login_time: '',
        role: '',
        permissions: [],
        settings: {}
      }
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('isLogin')
    },
    
    // 更新用户信息
    setUserInfo(userInfo) {
      this.userInfo = {
        ...this.userInfo,
        ...userInfo,
        // 兼容旧版本的role字段
        role: userInfo.user_type || userInfo.role || this.userInfo.role
      }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 更新用户头像
    setAvatar(avatar) {
      this.userInfo.avatar = avatar
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 更新用户设置
    updateSettings(settings) {
      this.userInfo.settings = {
        ...this.userInfo.settings,
        ...settings
      }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 更新最后登录时间
    updateLastLoginTime() {
      this.userInfo.last_login_time = new Date().toISOString()
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 从本地存储初始化
    initFromStorage() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      const isLogin = localStorage.getItem('isLogin')
      
      if (token && userInfo && isLogin === 'true') {
        try {
          const parsedUserInfo = JSON.parse(userInfo)
          this.isLogin = true
          this.token = token
          this.userInfo = {
            ...this.userInfo,
            ...parsedUserInfo,
            // 兼容旧版本的role字段
            role: parsedUserInfo.user_type || parsedUserInfo.role || 'user'
          }
        } catch (error) {
          console.error('解析用户信息失败:', error)
          this.logout()
        }
      }
    },
    
    // 检查用户权限
    checkPermission(permission) {
      return this.hasPermission(permission)
    },
    
    // 检查多个权限（任一满足即可）
    checkAnyPermission(permissions) {
      return permissions.some(permission => this.hasPermission(permission))
    },
    
    // 检查多个权限（全部满足）
    checkAllPermissions(permissions) {
      return permissions.every(permission => this.hasPermission(permission))
    }
  }
}) 